import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/finance/widgets/month_item.dart';
import 'package:family_app/src/features/finance/screens/accounting_screen.dart';
import 'package:family_app/src/features/finance/screens/stats_screen.dart';
import 'package:family_app/src/features/finance/screens/budget_screen.dart';
import 'package:family_app/src/theme/app_theme.dart';
import 'package:family_app/src/features/finance/providers/finance_provider.dart';

/// 首页屏幕
/// 显示资产概览、年份选择、月份列表
class HomeScreen extends ConsumerStatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends ConsumerState<HomeScreen> {
  /// 选中的年份
  int selectedYear = DateTime.now().year;
  
  /// 选中的底部导航栏索引
  int _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_getAppBarTitle()),
        elevation: 0,
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: _buildBody(),
      bottomNavigationBar: _buildBottomNavigationBar(),
    );
  }
  
  /// 获取 AppBar 标题
  String _getAppBarTitle() {
    switch (_selectedIndex) {
      case 0:
        return '首页';
      case 1:
        return '记账';
      case 2:
        return '统计';
      case 3:
        return '预算';
      default:
        return '首页';
    }
  }
  
  /// 构建主体内容
  Widget _buildBody() {
    switch (_selectedIndex) {
      case 0:
        return _buildHomeContent();
      case 1:
        return const AccountingScreen();
      case 2:
        return const StatsScreen();
      case 3:
        return const BudgetScreen();
      default:
        return _buildHomeContent();
    }
  }
  
  /// 构建首页内容
  Widget _buildHomeContent() {
    return Column(
      children: [
        // 固定顶部：本年收入和支出
        _buildYearlyStats(),
        
        // 固定中部：年份选择器
        _buildYearSelector(),
        
        // 可滑动部分：月份列表
        Expanded(
          child: _buildScrollableMonthList(),
        ),
      ],
    );
  }
  
  /// 构建本年收入和支出统计
  /// 根据 /bill/year/money 接口获取真实数据
  Widget _buildYearlyStats() {
    // 监听年度统计数据（userId 暂时使用 1，可根据实际情况修改）
    final yearlyStatsAsync = ref.watch(yearlyStatsProvider((selectedYear, 1)));

    return Container(
      padding: EdgeInsets.all(16.w),
      child: yearlyStatsAsync.when(
        data: (yearlyStats) {
          // 格式化金额显示（API返回的已经是元单位，无需转换）
          final incomeText = yearlyStats != null
              ? '¥ ${yearlyStats.totalIncomeMoney.toStringAsFixed(2)}'
              : '¥ 0.00';
          final expenseText = yearlyStats != null
              ? '¥ ${yearlyStats.totalExpenseMoney.toStringAsFixed(2)}'
              : '¥ 0.00';

          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              // 本年收入
              Column(
                children: [
                  Text(
                    '本年收入',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    incomeText,
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.green,
                    ),
                  ),
                ],
              ),

              // 分割线
              Container(
                width: 1,
                height: 50.h,
                color: Colors.grey[300],
              ),

              // 本年支出
              Column(
                children: [
                  Text(
                    '本年支出',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    expenseText,
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.red,
                    ),
                  ),
                ],
              ),
            ],
          );
        },
        loading: () => Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            // 本年收入（加载中）
            Column(
              children: [
                Text(
                  '本年收入',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[600],
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 8.h),
                SizedBox(
                  width: 120.w,
                  height: 24.h,
                  child: LinearProgressIndicator(
                    backgroundColor: Colors.grey[200],
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.green.withOpacity(0.3)),
                  ),
                ),
              ],
            ),

            // 分割线
            Container(
              width: 1,
              height: 50.h,
              color: Colors.grey[300],
            ),

            // 本年支出（加载中）
            Column(
              children: [
                Text(
                  '本年支出',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[600],
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 8.h),
                SizedBox(
                  width: 120.w,
                  height: 24.h,
                  child: LinearProgressIndicator(
                    backgroundColor: Colors.grey[200],
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.red.withOpacity(0.3)),
                  ),
                ),
              ],
            ),
          ],
        ),
        error: (error, stack) => Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            // 本年收入（错误）
            Column(
              children: [
                Text(
                  '本年收入',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[600],
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 8.h),
                Icon(
                  Icons.error_outline,
                  size: 20.sp,
                  color: Colors.green[300],
                ),
              ],
            ),

            // 分割线
            Container(
              width: 1,
              height: 50.h,
              color: Colors.grey[300],
            ),

            // 本年支出（错误）
            Column(
              children: [
                Text(
                  '本年支出',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[600],
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 8.h),
                Icon(
                  Icons.error_outline,
                  size: 20.sp,
                  color: Colors.red[300],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
  
  /// 构建可滑动的月份列表
  /// 根据 /bill/list 接口返回的实际数据显示月份
  /// 如果某个月没有数据，列表不显示该月
  Widget _buildScrollableMonthList() {
    // 监听年度账单列表数据（userId 暂时使用 1，可根据实际情况修改）
    final monthlyBillsAsync = ref.watch(yearlyBillListProvider((selectedYear, 1)));

    return monthlyBillsAsync.when(
      data: (monthlyBills) {
        // 如果没有数据，显示空状态
        if (monthlyBills.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.inbox,
                  size: 64.sp,
                  color: Colors.grey[300],
                ),
                SizedBox(height: 16.h),
                Text(
                  '暂无账单数据',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          );
        }

        // 按月份倒序排序（12月到1月）
        final sortedBills = List.from(monthlyBills)
          ..sort((a, b) => int.parse(b.month).compareTo(int.parse(a.month)));

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
          itemCount: sortedBills.length,
          itemBuilder: (context, index) {
            final bill = sortedBills[index];
            final monthNumber = int.parse(bill.month);

            return MonthItem(
              monthNumber: monthNumber,
              income: bill.totalIncomeMoney.toDouble(),
              expense: bill.totalExpenseMoney.toDouble(),
              transactions: _getMonthTransactions(monthNumber),
            );
          },
        );
      },
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, stack) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64.sp,
              color: Colors.red[300],
            ),
            SizedBox(height: 16.h),
            Text(
              '加载账单失败',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.red[600],
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              error.toString(),
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[600],
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
  
  /// 构建底部导航栏
  Widget _buildBottomNavigationBar() {
    return BottomNavigationBar(
      currentIndex: _selectedIndex,
      onTap: (index) => setState(() => _selectedIndex = index),
      type: BottomNavigationBarType.fixed,
      items: const [
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          label: '首页',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.add_circle),
          label: '记账',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.bar_chart),
          label: '统计',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.account_balance_wallet),
          label: '预算',
        ),
      ],
    );
  }

  /// 构建年份选择器
  Widget _buildYearSelector() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12.r),
      ),
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 上一年按钮
          IconButton(
            onPressed: () => setState(() => selectedYear--),
            icon: Icon(
              Icons.chevron_left,
              color: AppTheme.primaryColor,
              size: 20.sp,
            ),
            tooltip: '上一年',
            constraints: BoxConstraints(minWidth: 36.w, minHeight: 36.h),
            padding: EdgeInsets.zero,
          ),

          // 年份显示
          Expanded(
            child: Center(
              child: Text(
                '$selectedYear 年',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),

          // 下一年按钮
          IconButton(
            onPressed: () => setState(() => selectedYear++),
            icon: Icon(
              Icons.chevron_right,
              color: AppTheme.primaryColor,
              size: 20.sp,
            ),
            tooltip: '下一年',
            constraints: BoxConstraints(minWidth: 36.w, minHeight: 36.h),
            padding: EdgeInsets.zero,
          ),
        ],
      ),
    );
  }

  /// 获取月份的交易数据（示例）
  List<Map<String, dynamic>> _getMonthTransactions(int month) {
    return [
      {'label': '餐饮消费', 'amount': -68.50},
      {'label': '购物消费', 'amount': -299.00},
      {'label': '工资收入', 'amount': 8500.00},
    ];
  }
}
